<template>
  <app-card>
    <template #header>
      <el-space :size="10" spacer="|">
        <el-button
            type="primary"
            @click="uploadMedia"
        >
          <el-icon>
            <uploadFilled/>
          </el-icon>
          上传图片
        </el-button>
        <el-button
            type="info"
            @click="allSelect"
        >
          <el-icon>
            <Select/>
          </el-icon>
          全选
        </el-button>
        <el-button
            type="danger"
            @click="batchDelete"
        >
          <el-icon>
            <delete/>
          </el-icon>
          删除图片
        </el-button>
        <el-button
            type="success"
            @click="loadList"
        >
          <el-icon>
            <refresh/>
          </el-icon>
          刷新图片
        </el-button>
      </el-space>
    </template>
    <div class="videoList" v-resize:100="resize" ref="viewerdom" v-loading="listLoading">
      <item :key="item.id" :item-width="itemWidth" v-model:show="item.show" v-model:checkedFlag="item.checked"
            :image-path="item.image"
            v-for="(item,index) in list">
        <span class="title">{{ item.fileName }}</span>
        <span class="name">上传时间：{{ item.createdAt }}</span>
        <span class="name">
          <a @click="showImage(index)">查看图片</a>
          <a @click="openImage(item.image)">打开图片</a>
        </span>
        <span class="name">
            原始：{{ bytesToSize(item.originalSize) }}  压缩：{{ bytesToSize(item.fileSize) }}
          </span>

      </item>
    </div>
    <app-pagination
        v-model:page="listParams.pageNum"
        v-model:limit="listParams.pageSize"
        :list-count="listCount"
        :load-list="loadList"
        :disabled="listLoading"
    />
  </app-card>

</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {getImageList} from '@/api/static';
import {ImageInfo} from "@/api/types/static";
import {IListParams} from "@/api/types/common";
import {bytesToSize} from "@/utils/constants";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import Item from '../component/Item.vue'
import {delFile, upload} from "@/api/upload"

import "viewerjs/dist/viewer.css";
import Viewer from "viewerjs";

const viewerdom = ref<HTMLDivElement>()

const list = ref<ImageInfo[]>([]);
const listCount = ref(0);
const listLoading = ref(false);
const listParams = reactive<IListParams>({
  pageNum: 1,
  pageSize: 20,
});

onMounted(() => {
  loadList();
});

const loadList = async () => {
  listLoading.value = true;
  const data = await getImageList(listParams).finally(() => {
    listLoading.value = false;
  });
  list.value = data.rows;
  listCount.value = data.total;
};

// 上传图片
const uploadMedia = () => {
  const input = document.createElement('input') as HTMLInputElement
  input.setAttribute('type', 'file')
  input.setAttribute('accept', '.jpg,.jpeg,.png')
  input.setAttribute('multiple', 'multiple')
  input.click()
  input.onchange = async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '上传中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    for (let i = 0; i < input.files!.length; i++) {
      await upload('image', input.files![i])
    }
    loading.close()
    ElMessage.success(`上传成功!`)
    await loadList()
  }
}

// 批量删除视频
const batchDelete = () => {
  const delList = list.value.filter((i) => {
    return i.checked
  }).map((i) => {
    return i.image
  })
  if (delList.length === 0) {
    ElMessage.warning(`请选择要删除的图片文件!`)
    return
  }
  ElMessageBox.confirm(
      '是否永久删除选择的图片！',
      '提醒', {confirmButtonText: '确认', cancelButtonText: '取消',})
      .then(async () => {
        for (const path of delList) {
          await delFile('image', path)
        }
        ElMessage.success(`图片已删除!`)
        await loadList()
      })
}

// 全选
const allSelect = () => {
  const flag = list.value[0]?.checked
  list.value.forEach((i) => {
    i.checked = !flag
  })
}

const showImage = (index: number) => {
  const viewer = new Viewer(viewerdom.value!, {
    title: false,
    hide: () => {
      viewer.destroy()
    }
  });
  viewer.view(index)
}

const openImage = (path: string) => {
  window.open(path)
}

const itemWidth = ref('250px')
const resize = (el: HTMLElement) => {
  const i = Math.floor(el.clientWidth / 250)
  if(i){
    itemWidth.value = Math.floor(el.clientWidth / i)-10+ 'px'
  }
}
</script>

<style lang="scss" scoped>

div.videoList {
  display: flex;
  justify-content: flex-start;
  align-content: center;
  flex-wrap: wrap;

  span {
    padding-left: 5px;
  }

  span.title {
    line-height: 30px;
  }

  span.name {
    line-height: 20px;

    a {
      color: #bcd5ec;
      margin-left: 30px;

      &:hover {
        color: #96cafa;
      }
    }
  }
}

</style>
